package com.fr.lintcode;

import java.util.ArrayList;
import java.util.List;

public class Q290 {

    /**
     * @param nums:
     *            the array of elements to be inserted.
     * @return: return the least operation number.
     */
    public long sortedArrangement(int[] nums) {
        // write your code here
        long count = 0;
        List<Integer> list = new ArrayList<>(nums.length);

        for (int i : nums) {
            int index = quickFind(list, i);
            int c = Math.min(list.size() - index, index);
            count = count + c * 2 + 1;
            list.add(index, i);
        }

        return count;
    }

    private int quickFind(List<Integer> list, int target) {
        int i = 0;
        int j = list.size() - 1;
        while (i <= j) {
            int tmp = (i + j) / 2;
            if (list.get(tmp) > target) {
                j = tmp - 1;
            } else {
                i = tmp + 1;
            }
        }
        return Math.max(i, j);
    }
}
